<!-- author: wjc -->
<!-- date: 2022-03-14 10:21:29 -->
<!-- description:  -->
<template>
  <a-breadcrumb style="margin: 16px 0">
    <a-breadcrumb-item v-for="(item, index) in breadcrumb">
      <router-link :to="item.link">{{ item.title }}</router-link>
    </a-breadcrumb-item>
    <a-breadcrumb-item v-if="title">{{ title }}</a-breadcrumb-item>
  </a-breadcrumb>
</template>

<script lang="ts" setup>
/*
面包屑组件
title : string / 可以为空
<vBreadcrumbVue :title=''></vBreadcrumbVue>
*/
import { ref,watch } from "vue";
import { useStore } from "vuex";
import { useRoute, useRouter } from "vue-router";

const store = useStore();
const path = ref<string>(useRoute().path);
const breadcrumb = ref<any[]>([]);

const props = defineProps({
  title: {
    type: String,
    default: "",
  },
  path: {
    type: String,
    default: "",
  },
});
//判断是否有传入链接地址
if (props.path != "") {
  path.value = props.path;
}
const init = () => {
  let setbr = setInterval(() => {
    if (Object.keys(store.state.abc.menu).length > 0) {
      breadcrumb.value = getopen(store.state.abc.menu, path.value);
      //判断是否有传入链接地址
      clearInterval(setbr);
    }
  });
};


//递归获取菜单
const getopen = (menu: Array<any>, path: string): any[] => {
  let arrPath: any[] = []; //路径保存
  let flag = false;
  let list: any[] = [];
  // 递归子集
  const children = (v2: any, arrPath: any, path: string) => {
    let flag = false;
    v2.forEach((res: any, index: number) => {
      if (res.link == path) {
        //初始化选中菜单
        let obj = { title: res.title, link: res.link };
        arrPath = [...arrPath, obj];
        flag = true;
      } else {
        if (!flag && v2.children && v2.children.length > 0) {
          let obj = { title: res.title, link: res.link };
          arrPath = [...arrPath, obj];
          const result = children(v2.children, arrPath, path);
          if (result) {
            flag = true;
          }
        }
      }
    });
    if (flag) {
      return arrPath;
    }
  };
  menu.forEach((res: any, index: number) => {
    let obj = { title: res.title, link: res.link };
    if (res.link == path) {
      //初始化选中菜单
      arrPath = [obj];
      flag = true;
    } else {
      if (!flag && res.children && res.children.length > 0) {
        arrPath = [obj];
        let result = children(res.children, arrPath, path);
        if (result) {
          list = result;
          flag = true;
        }
      }
    }
  });

  if (flag) {
    return list;
  } else {
    return [];
  }
};

init();
</script>
<script lang="ts">
export default {
  name: "v-breadcrumb",
};
</script>
<style scoped lang="less"></style>
